package com.hxl.tech.gateway.common.util;

import cn.hutool.core.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

/**
 * Redis
 * @author soliddq
 * @date 2023-09-20
 */
@Slf4j
public class RedisUtil {
    
    private static RedisTemplate redisTemplate;


    public RedisUtil() {
    }

    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisUtil.redisTemplate = redisTemplate;
    }

    public static boolean isExists(String key) throws RuntimeException {
        try {
            Boolean hasKey = redisTemplate.hasKey(key);
            return hasKey != null && hasKey;
        } catch (Exception var2) {
            var2.printStackTrace();
            throw new RuntimeException("redis异常");
        }
    }

    public static Set<String> getKeys(String pattern) {
        try {
            return redisTemplate.keys(pattern);
        } catch (Exception var2) {
            var2.printStackTrace();
            throw new RuntimeException("redis异常");
        }
    }

    public static Boolean setExpire(String key, int value, TimeUnit unit) {
        return redisTemplate.expire(key, (long) value, unit);
    }

    public static Boolean delete(String key) throws RuntimeException {
        try {
            redisTemplate.delete(key);
            return isExists(key) ? false : true;
        } catch (Exception var2) {
            var2.printStackTrace();
            throw new RuntimeException("redis异常");
        }
    }

    public static void set(String key, String value, int expire, TimeUnit unit) throws RuntimeException {
        try {
            redisTemplate.opsForValue().set(key, value);
            if (expire > 0) {
                setExpire(key, expire, unit);
            }

        } catch (Exception var5) {
            var5.printStackTrace();
            throw new RuntimeException("redis异常");
        }
    }

    public static void set(String key, Object value, int expire, TimeUnit unit) throws RuntimeException {
        try {
            redisTemplate.opsForValue().set(key, value);
            if (expire > 0) {
                setExpire(key, expire, unit);
            }

        } catch (Exception var5) {
            var5.printStackTrace();
            throw new RuntimeException("redis异常");
        }
    }

    public static Object get(String key) throws RuntimeException {
        try {
            return !isExists(key) ? null : redisTemplate.opsForValue().get(key);
        } catch (Exception var2) {
            var2.printStackTrace();
            throw new RuntimeException("redis异常");
        }
    }


}
